import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,

  Checkbox, DatePicker, Alert,Tooltip
} from 'antd';
import find from 'lodash/find';
import debounce from 'lodash/debounce';
import request from '@/utils/request';
import './index.less'
import config from '../../config/config'
import { download,formateObjToParamStr} from '@/utils/utils';

const FormItem = Form.Item;

@connect(({ staff_report, loading,global }) => ({
  staff_report,
  global,
  loading: loading.models.staff_report,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      maxWidth:200,
      all_users:[],
    };

  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      staff_report: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.ant-table-body');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        staff_report: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'staff_report/changeTableY',
      });
      dispatch({
        type: 'staff_report/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'staff_report/changeLoaded',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
    this.setState({
      maxWidth: document.querySelector('.table-page').offsetWidth-20
    },function () {
      console.log('maxWidth',this.state.maxWidth)
    })


    const that=this;
    request(`/revenue_statistics_users`,{
      method:'GET',
    }).then((response)=>{
      if(response.status===200){
        that.setState({
          all_users:response.data.data
        })
      }

    });

  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'staff_report/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    dispatch({
      type: 'staff_report/changeTableY',
    });
  };


  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'staff_report/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };
  handleExportReport=()=>{
    const {
      staff_report: { searchParams },
    } = this.props;
    console.log('searchParams',searchParams)
    download(`${config.prefix}/user_report_files?Authorization=Bearer ${sessionStorage.getItem('token')}&order_direction=desc&${formateObjToParamStr(searchParams)}`)

  }
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      staff_report: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label={'员工名称'}>
          {getFieldDecorator('user_ids', {
            initialValue: searchParams.user_ids,
          })(
            <Checkbox.Group style={{ width: '100%' }}>
              {
                this.state.all_users.map((item,index)=>{
                  return   <Checkbox key={index} value={item.id}>{item.username}</Checkbox>
                })
              }

            </Checkbox.Group>
          )}
        </FormItem>
        <br/>
        <FormItem label={'开始日期'}>
          {getFieldDecorator('start_date', {
            initialValue: moment(searchParams.start_date),
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem label={'结束日期'}>
          {getFieldDecorator('end_date', {
            initialValue: moment(searchParams.end_date),
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;
                console.log(fieldsValue)
                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                  start_date: moment(fieldsValue.start_date).format('YYYY-MM-DD'),
                  end_date: moment(fieldsValue.end_date).format('YYYY-MM-DD'),
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          <Tooltip title={'请先查询一次再导出'}>
              <Button
                className={'btn-green'}
                type="primary"
                icon="export"
                style={{ marginLeft: 8 }}
                onClick={this.handleExportReport}
              >导出报表
              </Button>
            </Tooltip>
        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'staff_report/add',
      payload: {
        ...formValues,
      },
      callback() {
        message.success('新建设备成功');
        that.setState({
          addModal: false,
        });
        const {
          staff_report: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      user_ids:[],
      start_date:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , "YYYY-MM-DD").format("YYYY-MM-DD"),
      end_date:moment(new Date()).format('YYYY-MM-DD'),
    });
  };


  render() {
    const that = this;
    const {
      staff_report: { data, loading, tableY, meta, summary, selectedRowKeys, additional },
      global:{gridTableW}
    } = this.props;
    const columns = [
      {
        title: '日期',
        dataIndex: 'date',
        width: 100,
        fixed:'left'
      },
    ];
    let tableX=100
    if(data[0]&&data[0].items){
      for(let i=0;i<data[0].items.length;i++){
        let name=data[0].items[i].username
        columns.push( {
          title: name,
          className:`vendor-meter${i%4+1}`,
          children: [
            {
              title: '开户数',
              dataIndex:`total_count${i+1}`,
              width: 70,
              className:`vendor-meter${i%4+1}`,
              render:(text,record)=>{
                const findByName=find(record.items,(o)=>o.username===name)
                return findByName?findByName.open_account_count:''
              }
            },
            {
              title: '收费笔数',
              dataIndex:`normal_count${i+1}`,
              className:`vendor-meter${i%4+1}`,
              width: 75,
              render:(text,record)=>{
                const findByName=find(record.items,(o)=>o.username===name)
                return findByName?findByName.charge_count:''
              }
            },
            {
              title: '收费金额',
              dataIndex:`abnormality_count${i+1}`,
              className:`vendor-meter${i%4+1}`,
              width: 75,
              render:(text,record)=>{
                const findByName=find(record.items,(o)=>o.username===name)
                return findByName?Number(findByName.charge_amount).toFixed(2):''
              }
            },
          ]
        },)
      }
      tableX=100+(data[0].items.length*230)
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>员工报表</span>
      </div>
      <div className="table-page">
        <div className="table-condition">
          {this.renderSimpleForm()}
        </div>
        <div>
          <Table
            style={{color: '#fff',maxWidth:this.state.maxWidth+'px'}}
            className="custom-small-table meter-table vendor-meter staff-report"
            loading={loading}
            rowKey={'date'}
            dataSource={[...data].reverse()}
            columns={columns}
            pagination={false}
            size="small"
            scroll={{x: tableX, y: tableY}}
          />
        </div>


      </div>
    </div>;
  }
}

export default BasicList;
